import $ from "@jquery";
import {
  selectElementHelper,
  getBorderStatus,
  getSelectionElements,
} from "@utils";

export function getFrameDocument(frame_id = "ueditor_0") {
  return (
    frame_id &&
    document.getElementById(frame_id) &&
    document.getElementById(frame_id).contentWindow.document
  );
}

export function waitFor(
  conditionCallBack = undefined,
  callback = undefined,
  loopTimeStemp = 100
) {
  if (!conditionCallBack) return;

  if (!conditionCallBack()) {
    setTimeout(function () {
      waitFor(conditionCallBack, callback, loopTimeStemp);
    }, loopTimeStemp);
    return;
  }
  //放在nexttick 防止script 还没初始化完
  setTimeout(function () {
    callback && callback();
  }, loopTimeStemp);
}

/**
 *
 * @param {HTMLElement} toolbarElem
 */
export function extendToolBar(toolbarElem) {
  let toolBar = $(toolbarElem);
  $(toolBar).append(
    `<div id="ltr" class="edui-box edui-button edui-default custom-button"  style="cursor:pointer;">LTR</div>`
  );
  $(toolBar).append(
    `<div id="rtl" class="edui-box edui-button edui-default custom-button"  style="cursor:pointer;">RTL</div>`
  );
  $(toolBar).append(
    `<div id="fix" class="edui-box edui-button edui-default custom-button"  style="cursor:pointer;">Fix</div>`
  );

  //为了方便自定义 返回新增按钮列表
  return $(toolBar).children(".custom-button");
}

/**
 *
 * @param {Document} doc
 *  @return JQuery
 */
export function getChangeDirectionTarget(doc) {
  return $(doc).find(".shirkhan_clicked_target");
}

/**
 *@param {Document} doc
 * @param {"rtl"|"ltr"} direction
 */
export function handleDirectionChange(doc, direction = "inherit") {
  const selection = doc.getSelection();

  if (!selection.isCollapsed) {
    //顺路处理一下 选择区域的rtl,ltr
    getSelectionElements(doc).forEach((elem) => {
      $(elem).changeDirection(direction, true);
    });
  } else {
    let target = getChangeDirectionTarget(doc);
    target && target.changeDirection(direction, true);
  }
}

/**
 * 内容区域--确定目标元素
 */
export function handleUserSelectTargetElement() {
  //4. 内容区域--确定目标元素
  getBorderStatus(function ({ border_status }) {
    const selectionTarget = $(getFrameDocument()).find("body");
    selectElementHelper(selectionTarget);
    //描边框显示和隐藏逻辑
    if (!border_status) {
      selectionTarget.addClass("shirkhan_border_none");
    } else {
      selectionTarget.removeClass("shirkhan_border_none");
    }
  });
}
